<?php
/**
 * Controller de Leads.
 *
 * @author    Chavão <freela@chavao.net>
 * @copyright Copyright (c) 2011, Chavão
 * @version   0.1
 */

class LeadController extends AppController
{
    /**
     * @access private
     * @var array
     */
    private $p_arrStatus = array(1=>'Em aberto', 2=>'Convertido', 3=>'Reunião', 4=>'Aguardando', 5=>'S/ Conversão');
    /**
     * @access private
     * @var array
     */
    private $p_arrMeses = array('01' => 'jan', '02' => 'fev', '03' => 'mar', '04' => 'abr', '05' => 'mai', '06' => 'jun', '07' => 'jul', '08' => 'ago', '09' => 'set', '10' => 'out', '11' => 'nov', '12' => 'dez');

    /**
     * Método executado antes de qualquer action
     * @access public
     */
    public function beforeFilter()
    {
        if(!$this->Usuario->estaLogado()) $this->redirect('/usuario/login');

        // Setar variáveis para a GUI
        $this->set('arrStatus', $this->p_arrStatus);
        $this->set('arrMeses', $this->p_arrMeses);
    }

    /**
     * Controller index
     * @access public
     */
    public function index()
    {
        $this->layout = "default.novo";
        $this->bCampoBusca = true;

        if( $this->param('exibir') )
        {
            $_SESSION['paginate_exibir'] = $this->param('exibir');
        }

        $_SESSION['paginate_exibir'] = 10000;

        $sUser = ( $this->Usuario->ehAdmin() ) ? 'ADMIN' : 'USER';

        $arrLead = array();

        // Montando critérios
        $sCriterio = $this->montarCriterio();
 
        if( $sUser == 'ADMIN' )
        {
            $arrUsuario = $this->Usuario->buscarTodosUsuarios();

            $this->set('arrUsuario', $arrUsuario);
        }
        $arrLead = $this->Lead->buscarLeads( $sCriterio, $sUser, $this->page() );
        $sSliceChart = $this->Lead->montarJSONGrafico( $this->p_arrStatus );
        $sTempoMedio = $this->Lead->tempoMedio();
        $iLeadsAtendidos = $this->Lead->totalLeadsAtendidos();
        $iTotalLeads = $this->Lead->totalLeads();
        $iTotalVendas = $this->Lead->totalVendas();
        $iValorLead = $this->Lead->valorLead();
        
        // Setar variáveis para a GUI
        $this->set('bAddLead', $this->Lead->podeAddLead());
        $this->set('arrCampanhasInativas', $this->Campanha->listarTodasCampanhasInativas());
        $this->set('arrCampanhasAtivas', $this->Campanha->listarTodasCampanhas());
        $this->set('arrLead', $arrLead);
        $this->set('sSliceChart', $sSliceChart);
        $this->set('sTempoMedio', $sTempoMedio);
        $this->set('iLeadsAtendidos', $iLeadsAtendidos);
        $this->set('iTotalLeads', $iTotalLeads);
        $this->set('iTotalVendas', $iTotalVendas);
        $this->set('iValorLead', $iValorLead);
        $this->set('sUser', $sUser);

    }

    /**
     * Controller adicionar
     * @access public
     */
    public function adicionar()
    {
        $this->layout = "default.novo";
        $this->bCampoBusca = false;

        if(!empty($this->data))
        {
            if( $this->Usuario->ehAdmin() )
            {
                $oCamp = $this->Campanha->first(array(
                            'conditions' => array( 'camp_id' => $this->data['camp_id'] )
                ));
                if($oCamp['camp_fila'])
                {
                    $oLead = $this->Lead->first(array(
                            'conditions' =>  array( 'camp_id='.$this->data['camp_id']." order by lead_entrada desc" )
                    ));
                    if($oLead['usua_id'] > 0) 
                    {
                        $arrUsuarios = $this->Usuario->all(array(
                            'conditions' => array( 'clie_id='.$oCamp['clie_id']." and (usua_ativo = 1) order by usua_id asc" )
                        ));
                        foreach ($arrUsuarios as $key => $usuario) 
                        {
                            if($usuario['usua_id'] == $oLead['usua_id']) 
                            {
                                if(($key+1) >= count($arrUsuarios))
                                    $this->data['usua_id'] = $arrUsuarios[0]['usua_id'];
                                else
                                     $this->data['usua_id'] = $arrUsuarios[$key+1]['usua_id'];
                                $this->Lead->adicionar( $this->data, $this->Usuario->ehAdmin() );
                                $this->redirect('/lead');
                                return;
                            }
                        }
                    }
                    else
                    {
                        $oUsuario = $this->Usuario->first(array(
                            'conditions' => array( 'clie_id='.$oCamp['clie_id']." order by usua_id asc" )
                        ));
                        $this->data['usua_id'] = $oUsuario['usua_id'];
                    }
                }
           }
           $this->Lead->adicionar( $this->data, $this->Usuario->ehAdmin() );
           $this->redirect('/lead');
        }
        
        // Setar variáveis para a GUI
        $this->set('arrOrigem', $this->Origem->all());
        $this->set('arrCampanha', $this->Campanha->listarTodasCampanhas());
    }

    /**
     * Controller editar
     * @access public
     * @param integer $piLeadId Número do ID do lead para edição
     */
    public function editar($piLeadId = null, $piCampId = null)
    {
        $this->layout = "default.novo";
        $this->bCampoBusca = false;

        if(($piLeadId == null) or ($piCampId == null)) 
            $this->redirect('/lead');

        $arrCampanha = $this->Campanha->first(array(
					'conditions' => array('camp_id' => $piCampId)
        ));
        
        if($arrCampanha['clie_id'] != $_SESSION['cliente_id'])
             $this->redirect('/lead');
       
        if( !empty( $this->data ) )
        {
            if(isset($this->data['lead_nascimento']))
                $this->data['lead_nascimento'] = $this->inverterData($this->data['lead_nascimento'], '-');

            /*if( ( trim( $this->data['lead_atendimento'] ) != '' ) && ( $this->data['lead_status'] != 1 ) )
             {
             $this->data['lead_atendimento'] = $this->inverterData( $this->data['lead_atendimento'], '-', true );
             }*/
            $this->Lead->id = $piLeadId;
            $this->Lead->save($this->data);
            $this->LogLeadControl->gravarLog('lead','editar lead',"lead_id:".$piLeadId);
            $this->redirect('/lead');
        }

        $objLead = (object) $this->Lead->first(array(
					'conditions' => array('lead_id' => $piLeadId)
        ));

        $dtMenor = $objLead->lead_entrada;
        $dtMaior = $objLead->lead_atendimento;
        if( trim($dtMaior)!='' )
        {
            $objLead->tempo_resposta = $this->difData($dtMaior, $dtMenor);
        }

        // Setar variáveis para a GUI
        $this->set('objLead', $objLead);
        $this->set('arrOrigem', $this->Origem->all());
    }

    /**
     * Montar critérios de listagem específico para Leads
     * @access private
     * @return string Critérios para serem usados na consulta
     */
    private function montarCriterio()
    {
        $sCriterio = '';

        // Filtro por status do lead
        if(trim($this->param('status')!=''))
        {
            $sCriterio = "(lead_status = '".$this->param('status')."') AND ";

            if( $this->param('status') != 0 )
            {
                $_SESSION['filtro_status'] = $this->param('status');
            }
            else
            {
                $sCriterio = '';

                $_SESSION['filtro_status'] = '';
            }
        }
        else if((isset($_SESSION['filtro_status'])) && (trim($_SESSION['filtro_status']!='')))
        {
            $sCriterio .= "(lead_status = '".$_SESSION['filtro_status']."') AND ";
        }

        unset($_SESSION['data1']);
        unset($_SESSION['data2']);
        // Filtro por range de datas
        if((trim($this->param('data1'))!='') && (trim($this->param('data2'))!='') && (trim($this->param('data1'))!='-undefined-undefined') && (trim($this->param('data2'))!='-undefined-undefined')) {
            $sData1 = str_replace('-','/',$this->param('data1'));
            $sData2 = str_replace('-','/',$this->param('data2'));

            $sCriterio .= "(lead_entrada >= '".$this->inverterData($sData1,'-')." 00:00:00' AND lead_entrada <= '".$this->inverterData($sData2,'-')." 23:59:59') AND ";
        } else if(
                (isset($_SESSION['data1']))
                &&
                (isset($_SESSION['data2']))
                &&
                (trim($_SESSION['data1'])!='')
                &&
                (trim($_SESSION['data2'])!='')
                )
        {
            $sData1 = str_replace('-','/',$_SESSION['data1']);
            $sData2 = str_replace('-','/',$_SESSION['data2']);

            $sCriterio .= "(lead_entrada >= '".$this->inverterData($sData1,'-')." 00:00:00' AND lead_entrada <= '".$this->inverterData($sData2,'-')." 23:59:59') AND ";
        }

        // Filtro por campanha
        if(trim($this->param('campanha')!=''))
        {
            if( $this->param('campanha') != 0 )
            {
                $sCriterio .= "(camp_id = '".$this->param('campanha')."') AND ";

                $_SESSION['filtro_campanha'] = $this->param('campanha');
            }
            else
            {
                $_SESSION['filtro_campanha'] = '';
            }
        }
        else if((isset($_SESSION['filtro_campanha'])) && (trim($_SESSION['filtro_campanha']!='')))
        {
            $sCriterio .= "(camp_id = '".$_SESSION['filtro_campanha']."') AND ";
        }
        // Filtro por estado
        if(trim($this->param('estado')!=''))
        {
            
            if( $this->param('estado') != '0' )
            {
                $sCriterio .= "(lead_estado = '".$this->param('estado')."') AND ";
                $_SESSION['filtro_estado'] = $this->param('estado');
            }
            else
            {
                $_SESSION['filtro_estado'] = '';
            }
        }
        else if((isset($_SESSION['filtro_estado'])) && (trim($_SESSION['filtro_estado']!='')))
        {
            $sCriterio .= "(lead_estado = '".$_SESSION['filtro_estado']."') AND ";
        }
        // Filtro por busca
        if( trim( $this->param('search') ) != '' )
        {
            $sCriterio .= "(lead_nome LIKE '%".$this->param('search')."%') AND ";
        }
        return substr($sCriterio,0,-5);
    }
    /**
     * Processa lead por requisição AJAX
     * @param integer $piLeadId Número do ID do lead para processamento
     * @return string JSON para exibição
     */
    public function processar( $piLeadId = null )
    {
        $this->autoRender = false;
        echo "Lead ID:".$piLeadId;

        $arrSave = array();

        $arrSave['lead_id'] = $piLeadId;
        date_default_timezone_set('America/Sao_Paulo');
        $arrSave['lead_atendimento'] = date('Y-m-d H:i:s');
        $arrSave['lead_status'] = 4; // Status: Aguardando

        $this->Lead->save($arrSave);

        $objLead = (object) $this->Lead->first(array(
					'conditions' => array('lead_id' => $piLeadId)
        ));

        $dtMenor = $objLead->lead_entrada;
        $dtMaior = $objLead->lead_atendimento;

        $sTempoResposta = $this->difData($dtMaior, $dtMenor);
        $sJSON = '{';
        $sJSON .= "'data_atendimento':'".substr($objLead->lead_atendimento,8,2).' '.$this->p_arrMeses[substr($objLead->lead_atendimento,5,2)].'/'.substr($objLead->lead_atendimento, 11,5)."'";
        $sJSON .= ",'tempo_resposta':'".$sTempoResposta."'";
        $sJSON .= '}';

        // Return para o AJAX
        ob_clean();
        echo $sJSON;
    }

    /**
     * Altera status do lead por requisição AJAX
     * @access public
     * @return string JSON para exibição
     */
    public function alterarStatus()
    {
        $this->autoRender = false;

        $iLeadId = $this->param('lead_id');
        $iStatusId = $this->param('status_id');

        $objLead = (object) $this->Lead->first(array(
					'conditions' => array('lead_id' => $iLeadId)
        ));

        $arrSave['lead_id'] = $iLeadId;
        $arrSave['lead_status'] = $iStatusId;

        if( $objLead->lead_status == 1 )
        {
            date_default_timezone_set('America/Sao_Paulo');
            $arrSave['lead_atendimento'] = date('Y-m-d H:i:s');

            $this->Lead->save($arrSave);

            $objLead = (object) $this->Lead->first(array(
						'conditions' => array('lead_id' => $iLeadId)
            ));

            $dtMenor = $objLead->lead_entrada;
            $dtMaior = $objLead->lead_atendimento;

            $sTempoResposta = $this->difData($dtMaior, $dtMenor);

            $sJSON = '{';
            $sJSON .= "'data_atendimento':'".substr($objLead->lead_atendimento,8,2).' '.$this->p_arrMeses[substr($objLead->lead_atendimento,5,2)].'/'.substr($objLead->lead_atendimento, 11,5)."'";
            $sJSON .= ",'tempo_resposta':'".$sTempoResposta."'";
            $sJSON .= '}';
        }
        else
        {
            $sJSON = '';

            if( $iStatusId != 1 )
            {
                $this->Lead->save($arrSave);
            }
        }
        // Return para o AJAX
        ob_clean();
        echo $sJSON;
    }

    /*
     * Encaminhar Lead para um Usuário por AJAX
     * @access public
     */
    function encaminharLead()
    {
        $this->autoRender = false;

        if( trim($this->data['lead_id']) != '' && trim($this->data['usua_id']) != '' )
        {
            $this->Lead->id = $this->data['lead_id'];
            $this->Lead->save($this->data);
        }
    }

    /**
     * Enviar Apresentação por email por AJAX
     * @access public
     */
    public function enviarAP()
    {
        /*
         * Pegar documento de uma campanha pelo ID
         * Pegar usuário pelo ID
         *
         * Enviar email para usuário com documento anexo.
         */
        $this->autoRender = false;

        $iLeadId = $this->param('lead_id');
        $iCampId = $this->param('camp_id');

        $objCamp = (object) $this->Campanha->first(array(
						'conditions' => array('camp_id' => $iCampId)
        ));

        if( trim($objCamp->camp_arquivo) == '' )
        {
            ob_clean();
            echo "Essa campanha não tem arquivo de apresentação!";
        }
        else
        {
            $objLead = (object) $this->Lead->first(array(
							'conditions' => array('lead_id' => $iLeadId)
            ));

            // Processar e enviar o email
            require_once dirname(__FILE__).'/../lib/phpmailer/class.phpmailer.php';

            $mail = new PHPMailer();

            $mail->IsSMTP();
            $mail->SMTPSecure = "ssl";
            $mail->Port       = 465;
            $mail->SMTPDebug  = 1;
            $mail->SMTPAuth   = true;
            $mail->Host       = SMTP_HOST;
            $mail->Port       = SMTP_PORT;
            $mail->Username   = SMTP_USER;
            $mail->Password   = SMTP_PASS;

            $mail->SetFrom(SMTP_USER, SMTP_NAME);

            $mail->Subject    = $objCamp->camp_nome;
            $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
            
            if(isset($objCamp->camp_email_txt))
            {
                $formattedPost = str_replace("\n", "<br>", $objCamp->camp_email_txt); 
                $body ="<p>".$formattedPost."</p>";
            }  
            else
                $body = "<p>&nbsp;</p>";
            
            $mail->MsgHTML($body);

            $mail->AddAddress($objLead->lead_email);

            $mail->AddAttachment(dirname(__FILE__).'/../webroot/uploads/'.$objCamp->camp_arquivo);

            ob_clean();
            if($mail->Send())
            {
                echo "Arquivo enviado com sucesso!";
            }
            else
            {
                echo "Falha no envio do email, tente novamente!";
            }
        }
    }

    /**
     * Enviar relatório por email
     * @access public
     */
    public function enviarRelatorio()
    {
        $this->layout = 'vazio';

        if( !empty($this->data) )
        {
            if($this->data['send_email'] != "")
            {
            $sUser = ( $this->Usuario->ehAdmin() ) ? 'ADMIN' : 'USER';

            $arrLead = array();

            // Montando critérios
            $sCriterio = $this->montarCriterio();

            if( $sUser == 'ADMIN' )
            {
                $arrUsuario = $this->Usuario->buscarTodosUsuarios();

                $this->set('arrUsuario', $arrUsuario);
            }

            $arrLead = $this->Lead->buscarLeads( $sCriterio, $sUser, $this->page() );
            $sSliceChart = $this->Lead->montarJSONGrafico( $this->p_arrStatus );
            $sTempoMedio = $this->Lead->tempoMedio();
            $iLeadsAtendidos = $this->Lead->totalLeadsAtendidos();
            $iTotalLeads = $this->Lead->totalLeads();
            $iTotalVendas = $this->Lead->totalVendas();
            $iValorLead = $this->Lead->valorLead();


            $body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
					<html xmlns="http://www.w3.org/1999/xhtml">
					<head>
					    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
					    <title>Tela "Lead"</title>
					</head>

					<body>
					    <div style="width: 100%; margin: 0;">
					        <div style="overflow: hidden;">
					            <div style="float: left; width: 212px; height: 91px; overflow: hidden;">
					                <img src="images/logo-lead-control-print.png" />
					            </div>
					            <div style="text-align: center;">
					                <h1 style=\'font-family: "Trebuchet MS"; font-size:  25px; color: #9dca15;\'>Leads</h1>
					            </div>
					        </div>

					        <hr style="border: none;  border-bottom: 5px solid #9dca15;" />

					        <table cellspacing="1" style="width: 100%; margin-bottom: 25px;">
					            <colgroup>
					                <col width="15%" />
					                <col />
					                <col width="20%" />
					                <col width="10%" />
					                <col width="22%" />
					                <col width="10%" />
					            </colgroup>
					            <thead>
					                <tr>
					                    <th style="background-color: #9dca15; color: #fff; font-family: \'Trebuchet MS\'; font-size: 14px; font-weight: bold; padding: 4px;">Entrada de lead</th>
					                    <th style="background-color: #9dca15; color: #fff; font-family: \'Trebuchet MS\'; font-size: 14px; font-weight: bold; padding: 4px;">Nome</th>
					                    <th style="background-color: #9dca15; color: #fff; font-family: \'Trebuchet MS\'; font-size: 14px; font-weight: bold; padding: 4px;">Telefone</th>
					                    <th style="background-color: #9dca15; color: #fff; font-family: \'Trebuchet MS\'; font-size: 14px; font-weight: bold; padding: 4px;">Data/Hora</th>
					                    <th style="background-color: #9dca15; color: #fff; font-family: \'Trebuchet MS\'; font-size: 14px; font-weight: bold; padding: 4px;">Tempo de resposta</th>
					                    <th style="background-color: #9dca15; color: #fff; font-family: \'Trebuchet MS\'; font-size: 14px; font-weight: bold; padding: 4px;">Status</th>
					                </tr>
					            </thead>
					            <tbody>';

            foreach( $arrLead as $objLead )
            {
                $objLead = (object) $objLead;

                $hsLeadEntrada = substr($objLead->lead_entrada,8,2).' '.$this->p_arrMeses[substr($objLead->lead_entrada,5,2)].'/'.substr($objLead->lead_entrada, 11,5);
                $hsLeadNome = $objLead->lead_nome;
                $hsLeadTelefone = $objLead->lead_telefone;
                $hsLeadAtendimento = ( trim($objLead->lead_atendimento) != '' ) ? substr($objLead->lead_atendimento,8,2).' '.$this->p_arrMeses[substr($objLead->lead_atendimento,5,2)].'/'.substr($objLead->lead_atendimento, 11,5) : '--';
                $hsTempoResposta = $objLead->tempo_resposta;
                $hsStatus = $this->p_arrStatus[$objLead->lead_status];

                $body .= '<tr>
					                    <td style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 12px; padding: 3px; text-align: center;">'.$hsLeadEntrada.'</td>
					                    <td style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 12px; padding: 3px; text-align: left;">'.$hsLeadNome.'</td>
					                    <td style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 12px; padding: 3px; text-align: left;">'.$hsLeadTelefone.'</td>
					                    <td style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 12px; padding: 3px; text-align: left;">'.$hsLeadAtendimento.'</td>
					                    <td style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 12px; padding: 3px; text-align: left;">'.$hsTempoResposta.'</td>
					                    <td style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 12px; padding: 3px; text-align: left;">'.$hsStatus.'</td>
					                </tr>';
            }

            $body .= '</tbody>
					        </table>

					        <table cellspacing="1" class="desempenho" style="width: 100%; margin-bottom: 25px;">
					            <thead>
					                <tr>
					                    <th colspan="6" style="background-color: #9dca15; color: #fff; font-family: \'Trebuchet MS\'; font-size: 14px; font-weight: bold; padding: 4px; text-align: left;">Índices de desempenho</th>
					                </tr>
					            </thead>
					            <tbody>
					                <tr>
					                    <td colspan="2" style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 14px; padding: 9px; text-align: center;">
					                        Leads recebidos
					                        <b>'.$iTotalLeads.'</b>
					                    </td>
					                    <td colspan="2" style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 14px; padding: 9px; text-align: center;">
					                        Leads atendidos
					                        <b>'.$iLeadsAtendidos.'</b>
					                    </td>
					                    <td colspan="2" style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 14px; padding: 9px; text-align: center;">
					                        Tempo Médio
					                        <b>'.$sTempoMedio.'</b>
					                    </td>
					                </tr>
					                <tr>
					                    <td colspan="3" style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 14px; padding: 9px; text-align: center;">
					                        Valor do lead
					                        <b>'.number_format($iValorLead, 2, ',', '.').'</b>
					                    </td>
					                    <td colspan="3" style="background-color: #e6f2c4; color: #414f16; font-family: \'Trebuchet MS\'; font-size: 14px; padding: 9px; text-align: center;">
					                        Total de Vendas
					                        <b>'.number_format($iTotalVendas, 2, ',', '.').'</b>
					                    </td>
					                </tr>
					            </tbody>
					        </table>
					    </div>
					</body>
					</html>';
                $sAssunto = ( empty(  $this->data['send_assunto'] ) ) ? 'Relatório de leads' : $this->data['send_assunto'];
                enviarEmail( $this->data['send_email'], $sAssunto, $body );
                ?><script> 
                    alert('Email enviado com sucesso!'); 
                    parent.closeModal(); 
                </script><?php
                //$this->redirect('/lead/1');
            } else {
                ?><script> 
                    alert('Ocorreu um erro no envio do email.'); 
                    parent.closeModal(); 
                </script><?php
                //$this->redirect('/lead/2');
            }
        }
    }
    
    /**
     * Controller exportar
     * @access public
     * @param string $psTipo Tipo de arquivo de importação
     */
    public function exportar( $psTipo = null )
    {
        $this->layout = 'vazio';

        if( $psTipo != null )
        {
            $this->autoRender = false;
            // Fazer a exportação


            $sUser = ( $this->Usuario->ehAdmin() ) ? 'ADMIN' : 'USER';

            $arrLead = array();

            // Montando critérios
            $sCriterio = $this->montarCriterio();

            if( $sUser == 'ADMIN' )
            {
                $arrUsuario = $this->Usuario->buscarTodosUsuarios();

                $this->set('arrUsuario', $arrUsuario);
            }

            $arrLead = $this->Lead->buscarLeads( $sCriterio, $sUser, $this->page() );

            $sTempoMedio = $this->Lead->tempoMedio();
            $iLeadsAtendidos = $this->Lead->totalLeadsAtendidos();
            $iTotalLeads = $this->Lead->totalLeads();
            $iTotalVendas = $this->Lead->totalVendas();
            $iValorLead = $this->Lead->valorLead();

            ?>

<table border='1' style='border-collapse: collapse;'>
	<tr>
		<th style='text-align: center;'>Entrada de lead</th>
		<th style='text-align: center;'>Nome</th>
		<th style='text-align: center;'>Telefone</th>
		<th style='text-align: center;'>E-mail</th>
		<th style='text-align: center;'>Data/Hora</th>
		<th style='text-align: center;'>Tempo de resposta</th>
		<th style='text-align: center;'>Status</th>
	</tr>

	<?php
    $sTrs = '';
	foreach( $arrLead as $objLead )
	{
	    $objLead = (object) $objLead;

	    $hsLeadEntrada = substr($objLead->lead_entrada,8,2).' '.$this->p_arrMeses[substr($objLead->lead_entrada,5,2)].'/'.substr($objLead->lead_entrada, 11,5);
	    $hsLeadNome = $objLead->lead_nome;
	    $hsLeadTelefone = $objLead->lead_telefone;
	    $hsLeadEmail = $objLead->lead_email;
	    $hsLeadAtendimento = ( trim($objLead->lead_atendimento) != '' ) ? substr($objLead->lead_atendimento,8,2).' '.$this->p_arrMeses[substr($objLead->lead_atendimento,5,2)].'/'.substr($objLead->lead_atendimento, 11,5) : '--';
	    $hsTempoResposta = $objLead->tempo_resposta;
	    $hsStatus = $this->p_arrStatus[$objLead->lead_status];
	    $sTrs.= '<tr>
		                    <td>'.$hsLeadEntrada.'</td>
		                    <td>'.$hsLeadNome.'</td>
		                    <td>'.$hsLeadTelefone.'</td>
		                    <td>'.$hsLeadEmail.'</td>
		                    <td>'.$hsLeadAtendimento.'</td>
		                    <td>'.$hsTempoResposta.'</td>
		                    <td>'.$hsStatus.'</td>
		                </tr>';
	}
	echo utf8_encode($sTrs);
	?>
</table>

<br />
<br />

<table border='1' style='border-collapse: collapse;'>
	<tr>
		<td>Leads recebidos</td>
		<td><?php echo $iTotalLeads; ?></td>
	</tr>
	<tr>
		<td>Leads atendidos</td>
		<td><?php echo $iLeadsAtendidos; ?></td>
	</tr>
	<tr>
		<td>Tempo médio</td>
		<td><?php echo $sTempoMedio; ?></td>
	</tr>
	<tr>
		<td>Valor do lead</td>
		<td><?php echo $iValorLead; ?></td>
	</tr>
	<tr>
		<td>Total de vendas</td>
		<td><?php echo $iTotalVendas; ?></td>
	</tr>
</table>

	<?php

	$sContent = ob_get_clean();

	switch( strtoupper( $psTipo ) )
	{
	    case 'PDF':
	        $this->salvarPDF( $sContent );
	        break;
	    case 'XLS':
	        $this->salvarXLS( $sContent );
	        break;
	}
        }
    }

    private function salvarXLS( $psCorpo )
    {
        date_default_timezone_set('America/Sao_Paulo');
        $sCorpo = utf8_decode( $psCorpo );
        $sNomeExcel = 'leadcontrol_'.date('d-m-Y');

        header('Expires: 0');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');
        header('Content-type: application/vnd.ms-excel;charset:UTF-8');
        header('Content-Disposition: attachment; filename='.$sNomeExcel.'.xls');
        print "\n";

        echo $sCorpo;
    }

    private function salvarPDF( $psCorpo )
    {
        require_once dirname(__FILE__).'/../lib/html2pdf/html2pdf.class.php';
        try
        {
            $html2pdf = new HTML2PDF('P', 'A4', 'pt');
            $html2pdf->writeHTML( $psCorpo );
            $html2pdf->Output('leadcontrol_'.date('d-m-Y').'.pdf');
            exit;
        }
        catch(HTML2PDF_exception $e) {
            echo $e;
            exit;
        }
    }
}

?>